﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Core.CMS.Providers
{
    public class CMSSiteMapProvider : SiteMapProvider
    {
        public override SiteMapNode FindSiteMapNode(string rawUrl)
        {
            string[] urlParts = rawUrl.Split("/".ToArray());
            int id = -1;
            int.TryParse(urlParts[urlParts.Length-1], out id);
            PageInfo info = PageInfo.Get(id);
            return CreateFromPageInfo(info);
        }

        public override SiteMapNodeCollection GetChildNodes(SiteMapNode node)
        {
            PageInfo nodePage = PageInfo.Get(int.Parse(node.Key));
            SiteMapNodeCollection results = new SiteMapNodeCollection();
            foreach (PageInfo childPage in nodePage)
            {
                results.Add(CreateFromPageInfo(childPage));
            }

            return results;
        }

        public override SiteMapNode GetParentNode(SiteMapNode node)
        {
            if (node.Key == "-1")
                return null;

            return CreateFromPageInfo(PageInfo.Get(int.Parse(node.Key)));
        }

        protected override SiteMapNode GetRootNodeCore()
        {
            return CreateFromPageInfo(PageInfo.HomePage);
        }

        SiteMapNode CreateFromPageInfo(PageInfo info)
        {
            if (info != null)
            {
                SiteMapNode node = new SiteMapNode(this, info.ID.ToString());
                node.Title = info.Title;
                node.Url = info.Url;
                return node;
            }

            return null;
        }
    }
}
